package org.tczs93.springsecurity.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;

/**
 * @author ：tao.li
 * @description：
 * @date ：Created in 2021/8/27 17:45
 */
@RestController
public class TestController {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private AuthenticationManager authenticationManager;

    @RequestMapping("/common/login")
    @ResponseBody
    public String login(String phone,String password){
        //这几行的效果是类似将springsecurity自带的登录页面参数存储起来,和CustomeUserDetailService
        //构建的User对象进行密码比对
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(phone, password);
        Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
         userDetailsService.loadUserByUsername(phone);
         //自定义token存储并返回,这里简单token为hello
        return "hello";
    }

    @GetMapping("/user/getInfo")
    @ResponseBody
    public String getInfo(){
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(principal.getUsername());
        return "getInfo";
    }

    @PostMapping("/user/post")
    @ResponseBody
    public String post(){
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(principal.getUsername());
        return "post";
    }

    @GetMapping("/admin/getUsers")
    @ResponseBody
    public String getUsers(){
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(principal.getUsername());
        return "getUsers";
    }
}
